# -*- coding: utf-8 -*-
# __author__ = 'sky'

from instanceApi import AwsIns
import socket
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import datetime
import subprocess
from configs import AWS_ACCOUNT_LIST, AWS_CONFIG
import time
import logging
import log

log.setup()
logger = logging.getLogger("main.ssr")
def send_email(names, msg):
    me_from = "platform_sre@tengzhangroup.com"
    me_pass = "xxxxxxxxxxx"

    ms = MIMEMultipart('alternative')
    now = datetime.datetime.now()
    st = now.strftime('%Y.%m.%d %H:%M')
    subject = "New SSR IP - %s" % (st)

    ms['Subject'] = subject
    ms['From'] = me_from

    part1 = MIMEText(msg, 'plain')
    ms.attach(part1)
    s = smtplib.SMTP('smtp.office365.com', 587)

    s.ehlo()
    s.starttls()
    s.login(me_from, me_pass)
    s.sendmail(me_from, names, ms.as_string())
    s.quit()

def get_result(*args):
    p = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE)
    for result in p.stdout.readlines():
        return result.strip()

def checkssrstatus(ip, port=10076):
    if ip == '3.101.49.178':
        return False
    sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sk.settimeout(1)
    result = sk.connect_ex((ip, port))
    if result == 0:
        return True
    else:
        return False

if __name__ == "__main__":
    #region = "us-west-1"
    # FORMAT = "%(asctime)-15s %(message)s"
    # logging.basicConfig(format=FORMAT, filename="./ssr.log", level=logging.INFO)
    # logger = logging.getLogger('ssr')

    names = ["79790562@qq.com","sreteam@tengzhangroup.com","bear.xiong@uptech.ai"]
    now = datetime.datetime.now()
    st = now.strftime('%Y.%m.%d %H:%M')
    for account in AWS_ACCOUNT_LIST:
            aws = AwsIns(account)
            instanceids = AWS_CONFIG[account].get("instanceids")
            for insid in instanceids:
                eip = aws.getEip(insid)
                logger.info("Now Ip Is:%s" % eip)
                if eip:
                    #判断ip是否通
                    for i in range(0, 5):
                        logger.info("%d times to test..." % (i))
                        time.sleep(2)
                        status = checkssrstatus(eip)
                        if status:
                            break
                    logger.info("ssr ip: %s status: %s" % (eip, status))
                    if status is False:
                        #对ip进行解绑
                        #获取getAssociationId
                        eip_l = []
                        eip_l.append(eip)
                        allid, assid = aws.getAid(eip_l)
                        #取消ip挂载
                        try:
                            aws.diassvpncIP(assid)
                            logger.info("dis eip:%s from ec2 success" % eip)
                        except Exception as e:
                            logger.error(e)
                        #对老的ip释放
                        try:
                            aws.relasevpcIP(allid)
                            logger.info("relaseeip:%s success" % eip)
                        except Exception as e:
                            logger.error(e)
                        try:
                            new_eip = aws.getvpcIP()
                            asseip = aws.assovpcIP(new_eip["AllocationId"], insid)
                            if asseip["ResponseMetadata"]["HTTPStatusCode"] == 200:
                                logger.info("Get New SSR Ip: %s" % (new_eip["PublicIp"]))
                                for i in range(0, 5):
                                    logger.info("%d times to test..." % (i))
                                    time.sleep(5)
                                    status = checkssrstatus(new_eip["PublicIp"])
                                    if status:
                                        # cmds = "/root/home_ansible/scripts/add_boss_iptables.sh %s" % (new_eip["PublicIp"])
                                        # result = get_result(cmds)
                                        # logger.info(result)
                                        text = "Dear All, \nSSR New Ip:%s\n" % (new_eip["PublicIp"])
                                        send_email(names, new_eip["PublicIp"])
                                        break
                        except Exception as e:
                            logger.error("create eip err and access to ec2 err")
                else:
                    try:
                        new_eip = aws.getvpcIP()
                        asseip = aws.assovpcIP(new_eip["AllocationId"], insid)
                        if asseip["ResponseMetadata"]["HTTPStatusCode"] == 200:
                            logger.info("Get New SSR Ip: %s" % (new_eip["PublicIp"]))
                            for i in range(0, 5):
                                logger.info("%d times to test..." % (i))
                                time.sleep(5)
                                status = checkssrstatus(new_eip["PublicIp"])
                                if status:
                                    # cmds = "/root/home_ansible/scripts/add_boss_iptables.sh %s" % (new_eip["PublicIp"])
                                    # result = get_result(cmds)
                                    # logger.info(result)
                                    text = "Dear All, \nSSR New Ip:%s\n" % (new_eip["PublicIp"])
                                    send_email(names, new_eip["PublicIp"])
                                    break
                    except Exception as e:
                        logger.error("create eip err and access to ec2 err")



